package com.carful.wx.controller;

import com.carful.cache.service.TokenCacheServiceImpl;
import com.carful.xigua.modules.common.entity.Rest;
import com.carful.xigua.modules.common.entity.RestBody;
import com.carful.wx.service.impl.WxH5ServiceImpl;
import com.carful.xigua.modules.common.util.JwtUtils;
import com.carful.xigua.modules.user.entity.User;
import com.carful.xigua.modules.user.service.impl.UserServiceImpl;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * wx/login
 * @author ad
 * Date 2024/7/12 9:17
 */


@RestController
@RequestMapping("/wx/h5")
public class WxH5Controller {

    @Autowired
    private WxH5ServiceImpl wxH5Service;

    @Autowired
    private TokenCacheServiceImpl tokenCacheService;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private JwtUtils jwtUtils;


    /**
     * 前端获取登录url
     */
    @GetMapping("/url")
    public Rest url() {
        String url = wxH5Service.getLoginUrl(null);
        return RestBody.okData(url);
    }


    /**
     * 微信code码登陆
     */
    @GetMapping("/wxLogin")
    public Rest wxLogin(@RequestParam("code")
                        @NotNull
                                String code,
                        @RequestParam("state")
                        @NotNull
                                String state) {
        String openid = wxH5Service.openid(code, state);
        User user = userService.getUserByOpenid(openid);
        String token = jwtUtils.generateToken(user.getUsername());
        tokenCacheService.put(state, token);
        return RestBody.okData(token);
    }

    /**
     * state值获取token
     */
    @GetMapping("/token")
    public Rest token(@RequestParam("state")
                        @NotNull
                                String state) {

        String token = tokenCacheService.get(state);

        return RestBody.okData(token);
    }

}
